package com.aube.video.ad;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aube.R;
import com.baidu.mobad.feeds.NativeErrorCode;
import com.baidu.mobad.feeds.RequestParameters;
import com.baidu.mobad.nativevideo.BaiduVideoNative;
import com.baidu.mobad.nativevideo.BaiduVideoResponse;
import com.baidu.mobads.AdSize;
import com.baidu.mobads.InterstitialAd;
import com.baidu.mobads.InterstitialAdListener;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.Utils;

import java.io.IOException;
import java.util.List;

/**
 * Created by huyaonan on 16/10/19.
 */
public class VideoAdHelper {

    private static final String TAG = "VIDEO_ADD";

    public static String AD_ID_FOR_PAUSE = "3036864";
    public static String AD_ID_FOR_PREPLAY = "3036848";

    private static int IMG_WIDTH = 400;
    private static int IMG_HEIGHT = 400;

    private IAdStateListener mAdListener;
    private Context context;
    private InterstitialAd mAd;
    private RelativeLayout mAdPause;
    private ImageView mAdImg;

    private BaiduVideoResponse mNrAd;
    private PrerollVideoLayout mVideoLayout;
    private RelativeLayout mAdContainer;
    private TextView mCountdownTxt;

    private int showState = -1;
    private static int CHECK_VISIBILITY = 0;
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == CHECK_VISIBILITY) {
                startConfig(mNrAd);
//                isReady = true;
                try {
                    showState = VisibilityChecker.getViewState(mAdContainer);
                    if (showState == VisibilityChecker.SHOW_STATE_SHOW) {
                        // 警告：调用该函数来发送展现，勿漏！
                        mNrAd.recordImpression(mAdContainer);
                        mVideoLayout.setVisibility(View.VISIBLE);
                        realPlay();
                    } else {
                        myHandler.sendEmptyMessageDelayed(CHECK_VISIBILITY, 1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            super.handleMessage(msg);
        }
    };

    public VideoAdHelper(Activity activity, IAdStateListener listener) {
        this.context = activity;
        this.mAdListener = listener;

//        mAdContainer = (RelativeLayout) activity.findViewById(R.id.ad_container);
//        mVideoLayout = (PrerollVideoLayout) activity.findViewById(R.id.ad_video);
//        mCountdownTxt = (TextView) activity.findViewById(R.id.ad_timecount);
//        mAdPause = (RelativeLayout) activity.findViewById(R.id.ad_pause);
//        mAdImg = (ImageView) activity.findViewById(R.id.ad_img);

        int screenHeight = SysUtil.getAbsoluteScreenHeight(activity);
        IMG_HEIGHT = IMG_WIDTH = screenHeight/2;

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAdPause.getLayoutParams();
        params.width = IMG_WIDTH;
        params.height = IMG_HEIGHT;

        mAdContainer.setVisibility(View.VISIBLE);
    }

    public static void setAdId(String pauseId, String prePlayId) {
        AD_ID_FOR_PAUSE = pauseId;
        AD_ID_FOR_PREPLAY = prePlayId;
    }

    /**
     * 创建暂停页广告
     */
    public void createAdForVideoPause() {
        if(mAd != null && mAd.isAdReady())
            return;

        mAd = new InterstitialAd(context, AdSize.InterstitialForVideoPausePlay, AD_ID_FOR_PAUSE);
        mAd.setListener(new InterstitialAdListener() {

            @Override
            public void onAdClick(InterstitialAd arg0) {
                Utils.Log(TAG, "onAdClick");
                if(mAdListener != null)
                    mAdListener.onPauseAdFinished();
            }

            @Override
            public void onAdDismissed() {
                Utils.Log(TAG, "onAdDismissed");
                if(mAdListener != null)
                    mAdListener.onPauseAdFinished();
            }

            @Override
            public void onAdFailed(String arg0) {
                Utils.Log(TAG, "onAdFailed");
            }

            @Override
            public void onAdPresent() {
                Utils.Log(TAG, "onAdPresent");
            }

            @Override
            public void onAdReady() {
                Utils.Log(TAG, "onAdReady");
            }

        });

        loadAd();
    }

    /**
     * 加载广告
     */
    private void loadAd() {
        mAd.loadAdForVideoApp(IMG_WIDTH, IMG_HEIGHT);
    }

    /**
     * 展示暂停广告
     */
    public void showAd() {
        if(mAd == null) {
            createAdForVideoPause();
            return;
        }
        if (mAd.isAdReady()) {
            mAdPause.setVisibility(View.VISIBLE);
            mAd.showAdInParentForVideoApp((Activity) context, mAdPause);
        } else {
//            loadAd();
            createAdForVideoPause();
        }
    }

    public void clearAd() {
        mAdContainer.setVisibility(View.GONE);
        mAdPause.setVisibility(View.GONE);

        mAdPause.removeAllViews();
        createAdForVideoPause();
    }

    public boolean isAdShowing() {
        return mAdContainer.getVisibility() == View.VISIBLE;
    }

    /**
     * 获取并展示播放前广告
     * @param activity
     */
    public void fetchAndShowAd(Activity activity) {
        /**
         * Step 1. 创建BaiduVideoNative对象，参数分别为： 上下文context，广告位ID,
         * BaiduVideoNetworkListener监听（监听广告请求的成功与失败）
         * 注意：请将YOUR_AD_PALCE_ID替换为自己的广告位ID
         */
        BaiduVideoNative baidu = new BaiduVideoNative(activity, AD_ID_FOR_PREPLAY, new BaiduVideoNative.BaiduVideoNetworkListener() {

            @Override
            public void onAdFail(NativeErrorCode arg0) {
                Utils.Log(TAG, "没有收到广告，请检查");
                frontAdFinished();
            }

            @Override
            public void onAdLoad(List<BaiduVideoResponse> arg0) {
                if (arg0 != null && arg0.size() > 0) {
                    mNrAd = arg0.get(0);
                    android.util.Log.i(TAG, "mNrAd.getMaterialType() is " + mNrAd.getMaterialType());
                    if (mNrAd.getMaterialType() == BaiduVideoResponse.PrerollMaterialType.VIDEO) {
                        Utils.Log(TAG, "收到视频广告:" + mNrAd.getVideoUrl() + ",duration:" + mNrAd.getDuration());
                        myHandler.sendEmptyMessage(CHECK_VISIBILITY);
                    } else if (mNrAd.getMaterialType() == BaiduVideoResponse.PrerollMaterialType.NORMAL) {
                        updateview(mNrAd);
                        Utils.Log(TAG, "收到图片贴片广告" + mNrAd.getImageUrl());
                    } else if (mNrAd.getMaterialType() == BaiduVideoResponse.PrerollMaterialType.GIF) {
                        // 自行渲染gif图片
                        updateview(mNrAd);
                        Utils.Log(TAG, "收到gif贴片广告" + mNrAd.getImageUrl());
                    } else {
                        Utils.Log(TAG, "物料类型不支持");
                    }
                }
            }

        });

        // /**
        // * Step 2. 创建requestParameters对象，并将其传给baidu.makeRequest来请求广告
        // */
        RequestParameters requestParameters = new RequestParameters.Builder()
                .setWidth(context.getResources().getDisplayMetrics().widthPixels)
                .setHeight((int) (250 * context.getResources().getDisplayMetrics().density))
                // .downloadAppConfirmPolicy(
                // RequestParameters.DOWNLOAD_APP_CONFIRM_ONLY_MOBILE) //
                // 用户点击下载类广告时，是否弹出提示框让用户选择下载与否
                .build();

        baidu.makeRequest(requestParameters);
    }

    private void realPlay() {
        Uri videoUri = Uri.parse(mNrAd.getVideoUrl());
        try {
            mVideoLayout.setVideoURI(videoUri);
            mVideoLayout.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    frontAdFinished();
                }
            });
//            firstPlay = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void frontAdFinished() {
        mAdContainer.setVisibility(View.GONE);
        //remove video
        mAdContainer.removeAllViews();
        createAdForVideoPause();
        if(mAdListener != null)
            mAdListener.onFinished();
    }

    private void startConfig(BaiduVideoResponse ad) {
        configAd(ad);
        mVideoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNrAd.handleClick(v, mVideoLayout.getCurrentPosition());
            }
        });
    }

    private void configAd(BaiduVideoResponse ad) {
        mVideoLayout.configTipView(ad.isDownloadApp());
        mVideoLayout.setTipViewClickedListener(new PrerollVideoLayout.TipViewClickedListener() {
            @Override
            public void onTipViewClicked(View v) {
                mNrAd.handleClick(v, mVideoLayout.getCurrentPosition());
            }
        });
    }

    private void updateview(final BaiduVideoResponse ad) {
        // 警告：调用该函数来发送展现，勿漏！
        ad.recordImpression(mAdContainer);
        mAdContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击响应
                ad.handleClick(view);
            }
        });
        mAdImg.setVisibility(View.VISIBLE);
        ImageLoader.getInstance(context).fillImage(mAdImg, ad.getImageUrl());

        int duration = ad.getDuration();
        if(duration  <= 0)
            duration = 10000;
        mCountdownTxt.setVisibility(View.VISIBLE);
        mCountdownTxt.setText(duration/1000+"");
        myHandler.postDelayed(runnable, 1000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Integer time = Integer.parseInt(mCountdownTxt.getText().toString());
            if (time > 0) {
                time--;
                mCountdownTxt.setText(time+"");
                myHandler.postDelayed(runnable, 1000);
            } else {
                frontAdFinished();
            }
        }
    };

    public interface IAdStateListener {
        public void onFinished();
        public void onPauseAdFinished();
    }

}
